<?php

class UserAction extends PublicAction
{

    public function login()
    {
        $this->display();
    }

    public function logout()
    {
        header('Content-Type:TEXT/HTML; charset=UTF-8');
        Session::set('login', false);
        $this->assign('jumpUrl', '/Index/index/');
        $this->assign('waitSecond', '3');
        $this->success('操作成功，将转至主页！');
    }

    public function info()
    {
        /**
         * Controller of User Center
         * Only an interface
         * Need reguser and upper privilege
         */
        $this->_verifyPrivilege(1);
        $navi = array(
            array(
                'URL' => U('User/changepsw'),
                'ID' => 'changepsw',
                'text' => '修改密码'),
            array(
                'URL' => U('User/changeemail'),
                'ID' => 'changeemail',
                'text' => '修改邮箱地址'),
            array(
                'URL' => U('User/showprivilege'),
                'ID' => 'showp',
                'text' => '查看权限'),
            array(
                'URL' => U('User/changeprivilege'),
                'ID' => 'changep',
                'text' => '修改用户权限'));
        $array = D('Privilegectrl')->getAllPrivilegeList();
        $this->assign('list', $array);
        $this->assign('UserNavi', $navi);
        $this->display();
    }

    public function changepsw()
    {
        /**
         * This function is the interface of changing password
         * The action executer is modifypsw() 
         */
        header('Content-Type:TEXT/HTML; charset=UTF-8');
        echo "<form action=" . U('User/modifypsw') . ' method="post" name="changepsw">';
        echo '<p>请输入旧密码<input name="oldpassword" type="password" /></p>
			<p>请输入新密码<input name="newpassword" type="password" /></p>
			<p>请确认新密码
			<input name="confirmpassword" type="password" />
			</p>
			<input type="submit" class="btnsubmit" value="提交" onmouseover="this.style.backgroundPosition=\'left -40px\'" onmouseout="this.style.backgroundPosition=\'left top\'" />
			</form>';
    }

    public function changeemail()
    {
        /**
         * This function is the interface of changing email
         * The action executer is modifyemail()
         */
        header('Content-Type:TEXT/HTML; charset=UTF-8');
        echo "<form action=" . U('User/modifyemail') . ' method="post" name="changeemail">';
        echo '<p>请输入新邮箱<input name="email" type="text" /></p>
			<input type="submit" class="btnsubmit" value="提交" onmouseover="this.style.backgroundPosition=\'left -40px\'" onmouseout="this.style.backgroundPosition=\'left top\'" />
			</form>';
    }
    
    public function modifypsw()
    {
        $old = sha1($_POST['oldpassword']);
        $new = sha1($_POST['newpassword']);
        $cnew = sha1($_POST['confirmpassword']);
        if($new <> $cnew)
            $this -> error("两次输入密码不一致！");
        $user = M('User') -> where('UID = '.$_SESSION['UID']) -> find();
        if($user['password'] <> $old)
            $this -> error('旧密码不匹配，如果您忘了密码，请点<a href="'.U('User/forget').'">这里</a>找回密码');
        //Success
        $user['password'] = $new;
        M('User') -> save($user);
        $this -> success("修改成功！");
    }
    
    public function modifyemail()
    {
        $new = $_POST['email'];
        if(preg_match("/.@./", $new))
            M("User") -> where("UID = ".$_SESSION['UID']) -> setField('email', $email);
        else
            $this -> error("邮箱格式不正确！");
        $this -> success("修改成功！");
    }

    public function showprivilege()
    {
        /**
         * This function is for showing what privilege do user have
         */
        echo "<ul>你拥有以下权限：";
        $p = D('Privilegectrl');
        $array = $p->select();
        foreach ($array as $i)
        {
            if ($i['level'] > $_SESSION['PLevel'])
                continue;
            echo "<li>" . $i['description'] . "</li>";
        }
        echo "</ul>";
    }

    public function changeprivilege()
    {
        /**
         * This function is the interface for changing privilege
         */
        $this->display();
    }

    public function ajaxuser()
    {
        /**
         * Find Editable user.
         * returned in ajax.
         */
        $choice = $_POST['query_type'];
        $keyword = $_POST['keyword'];
        $User = D("User");
        $P = D("Privilege");
        if ($choice == 'uid')
            $user = $User->where("UID = " . $keyword)->select();
        else
            $user = $User->where('username like "%' . $keyword . '%"')->select();
        foreach ($user as $i)
        {
            if ($i['UID'] == $_SESSION['UID'] || $P->getLevelFromID($i['PID']) >= $_SESSION['PLevel'])
                continue;
            echo '<tr>';
            echo '<td>' . $i['UID'] . '</td>';
            echo '<td>' . $i['username'] . '</td>';
            echo '<td>' . $i['truename'] . '</td>';
            echo '<td><a href="#" id="modify" class="modify">修改</a></td>';
            echo '</tr>';
        }
    }

    public function ajaxList()
    {
        /**
         * This function is for getting Modify List
         * returned in ajax
         */
        $Array = array();
        $P = D("Privilege");
        $P->where('PID <> 1')->select();
        foreach ($P as $i)
            if ($i['level'] < $_SESSION['PLevel'])
                echo '<option value="' . $i['PID'] . '">' . $i['descripion'] . '</option>\n';
    }

    public function verify()
    {
        header('Content-Type:TEXT/HTML; charset=UTF-8');
        $username = $_POST['username'];
        $password = $_POST['password'];
        $User = D('User');
        $P = D('Privilege');
        $user = $User->where('username = ' . '"' . $username . '"')->find();
        if (!isset($user['UID']))
            $this->error("用户名不存在!");
        else
        if (sha1($password) != $user['password'])
            $this->error("密码不正确！");
        //Success
        $_SESSION['login'] = true;
        //Session::setLocal('login', true);
        $_SESSION['UserName'] = $username;
        //Session::set('UserName', $username);
        //Session::setLocal('UserName', $username);
        $_SESSION['UID'] = $user['UID'];
        //Session::set('UID', $user['UID']);
        //Session::setLocal('UID', $user['UID']);
        $_SESSION['PLevel'] = $P->getLevelFromID($user['PID']);
        //Session::set('PLevel', $P -> getLevelFromID($user['PID']));
        $this->assign('jumpUrl', '/Index/index/');
        $this->assign('waitSecond', '3');
        //echo $_SESSION['PLevel'];
        $this->success('欢迎回来，将转至主页！');
    }

    public function profile()
    {
        /**
         * This function is an Ajax Return function
         */
        $User = D('User');
        $P = D('Privilege');
        $user = $User->where('UID = ' . $_SESSION['UID'])->find();
        $p = $P->where('PID = ' . $user['PID'])->find();
        echo '用户名：' . $user['username'] . '<br/>';
        echo '用户组：' . $p['description'] . '<br/>';
        echo '电子邮箱：' . $user['email'] . '<br/>';
        echo '真实姓名：' . $user['truename'] . '<br/>';
    }

    public function setP()
    {
        $PID = $_POST['plist'];
        $temp = M('Privilege') -> where('PID = '.$PID) -> find();
        if($temp['level'] > $_SESSION['PLevel'])
            echo "修改失败！请检查是否已经登陆超时？";
        else
        {
            $User = D('User');
            $User -> where('UID = '.$_POST['UID']) -> setField('PID', $PID);
            echo "修改成功！";
        }
    }
    
    public function getUsersFromUsername($name = "")
    {
        /**
         * This function return a list of users from Username
         * @var $name default is "", which indicates that the function should get it from $_POST['keyword']
         * @return an array, which lists the proper users by the keyword.
         */
        if($name == "")
            $name = $_POST['keyword'];
        $array = D('User') -> where('username = "'.$name.'"') -> select();
        if($_POST['out'] == true)
        {
            //Echo them out by table when $_POST['out'] == true
            foreach($array as $i)
            {
                echo '<tr>';
                echo '<td>'.$i['uid'].'</td>';
                echo '<td>'.'</td>';
                echo '<td>'.'</td>';
                echo '<td>'.'</td>';
            }
        }
        return $array;
    }
    
    public function getUsersFromUID($uid = -1)
    {
        /**
         * This function return a list of users from UID
         * @var $uid default is -1, which indicates that the function should get it from $_POST['keyword']
         * @return an array, which lists the proper users by the keyword
         */
        if($uid == -1)
            $uid = $_POST['keyword'];
        return D('User') -> where('uid = '.$uid) -> select();
    }
    
    public function getUsersFromTruename($name = "")
    {
        /**
         * This function return a list of users from Truename
         * @var $name default is "", which indicates that the function should get it from $_POST['keyword']
         * @return an array, which lists the proper users by the keyword.
         */
        if($name == "")
            $name = $_POST['keyword'];
        return D('User') -> where('truename = "'.$name.'"') -> select();
    }
    
    public function jsonUser()
    {
        $username = $_POST['username'];
        $type = $_POST['type'];
        if($type == 1)
        {
            $array = D('User')->where('PID <> 1 AND PID <>2 AND username like "%'.$username.'%"')->select();
            $this ->ajaxReturn($array);
        }
        else
        {
            $array = D('User')->where('PID <> 1 AND PID <>2 AND truename like "%'.$username.'%"');
            $this ->ajaxReturn($array);
        }
    }
    
    public function jsonVerifyUserGroup()
    {
        $pname = $_POST['group'];
        $level = D("Privilege") -> C($pname);
        if($_SESSION['PLevel'] < $level)
            $this -> ajaxReturn(false);
        else
            $this -> ajaxReturn(true);
    }
    
    public function jsonVerifyPrivilege()
    {
        $pname = $_POST['privilege'];
        $level = D("Privilegectrl") -> C($pname);
        if($_SESSION['PLevel'] < $level)
            $this -> ajaxReturn(false);
        else
            $this -> ajaxReturn(true);
    }
}

?>